package com.pine.common.database.listener;

import com.pine.common.database.annotations.DataPermission;
import com.pine.common.database.constant.DbDataScopeEnum;
import com.pine.common.util.user.UserInfo;
import com.pine.common.util.user.UserUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.expression.operators.relational.ParenthesedExpressionList;
import net.sf.jsqlparser.schema.Column;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 处理部门及子部门权限范围
 *
 * @author pine manage
 * @since 2024-09-26
 */
@Component
public class ProcessDeptWithChildrenDataScopeListener implements ProcessWhereExpressionListener {
    /**
     * 处理where条件
     *
     * @param where          where语句
     * @param dataPermission 权限注解
     * @param mainTableName  主表名/别名
     */
    @Override
    public Expression process(Expression where, DataPermission dataPermission, String mainTableName) {
        UserInfo userInfo = UserUtil.get();
        List<LongValue> deptIds = userInfo.deptIds().stream().map(LongValue::new).toList();
        ExpressionList<LongValue> deptIdsExpressionList = new ParenthesedExpressionList<>(deptIds);
        InExpression inExpression = new InExpression(new Column(mainTableName + "." + dataPermission.permissionFieldName()), deptIdsExpressionList);
        return new AndExpression(where, inExpression);
    }

    /**
     * 获取数据权限范围
     *
     * @return 数据权限范围
     */
    @Override
    public DbDataScopeEnum getDataScope() {
        return DbDataScopeEnum.DEPT_WITH_CHILDREN;
    }
}
